package com.lhkj.ct.meta.modules.report.word.group;

import cn.hutool.core.date.DateUtil;
import com.lhkj.ct.base.utils.file.word.xwpf.CustomXWPFDocument;
import com.lhkj.ct.base.utils.file.word.xwpf.ExportWord;
import com.lhkj.ct.meta.modules.psychology.model.vo.AnalysisResult;
import com.lhkj.ct.meta.modules.psychology.model.vo.DimenStatistics;
import com.lhkj.ct.meta.modules.report.AbstractReportHandle;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * 统计分析 word报告处理类
 */

public class GaugeStatisticsReportHandle extends AbstractReportHandle<AnalysisResult, XWPFDocument> {

    private final ExportWord word;

    public GaugeStatisticsReportHandle() {
        word = new ExportWord();
    }

    @Override
    public XWPFDocument generateReport(AnalysisResult data) {

        CustomXWPFDocument document = new CustomXWPFDocument();

        addCustomHeadingStyle(document, "title", 0);

        // step 1. 标题
        setTitle(document, data.getScaleName(), data.getGenerationDate());

        // step 2. 描述统计
        descriptiveStatistics(document, data.getGroupList());

        // step 3. 差异分析
        diffAnalysis(document, data.getDiversityList());

        // step 4. 结论
        conclusion(document, data.getConclusion());

        return document;

    }

    /**
     *  word 标题
     */
    private void setTitle(XWPFDocument document, String title, Date createTime) {

        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setStyle("title");
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setFontFamily("宋体");
        titleRun.setFontSize(24);
        titleRun.setBold(true);
        titleRun.setText(title);

        XWPFParagraph createTimePara = document.createParagraph();
        createTimePara.setAlignment(ParagraphAlignment.CENTER);
        createTimePara.setSpacingBetween(2, LineSpacingRule.AUTO);
        XWPFRun createTimeRun = createTimePara.createRun();
        createTimeRun.setFontFamily("宋体");
        createTimeRun.setFontSize(12);
        createTimeRun.setText("报告制作时间:" + DateUtil.format(createTime, "yyyy/MM/dd"));
    }

    /**
     *  描述统计
     */
    private void descriptiveStatistics(XWPFDocument document, List<AnalysisResult.Group> groupList) {
        // step 1.标题
        XWPFParagraph subTitle = document.createParagraph();
        subTitle.setSpacingBetween(3, LineSpacingRule.AUTO);
        XWPFRun subTitleRun = subTitle.createRun();
        subTitleRun.setFontFamily("宋体");
        subTitleRun.setFontSize(12);
        subTitleRun.setBold(true);
        subTitleRun.setText("一、描述统计");

        // step 2.创建表格
        long count = groupList.stream().mapToInt(u -> u.getDimenStatisticsList().size()).sum();
        XWPFTable table = document.createTable((int) (count + 1), 4);
        word.getXwpfTableHelper().setTableRowsHeight(table, 600, null);
        for (int i = 0; i < count + 1; i++) {
            word.getXwpfTableHelper().setTableRowBorder(table.getRow(i), STBorder.SINGLE, 1L, "DDDDDD");
            word.getXwpfTableHelper().setRowAlign(table.getRow(i), XWPFTableCell.XWPFVertAlign.CENTER, STJc.CENTER);
        }
        table.setWidth("100%");
        // step 3.设置表头内容和样式
        XWPFTableRow header = table.getRow(0);
        header.getCell(0).setText("团体");
        header.getCell(1).setText("维度");
        header.getCell(2).setText("平均值");
        header.getCell(3).setText("标准差");
        for (XWPFTableCell tableCell : header.getTableCells()) {
            tableCell.setColor("6CA1DD");
        }

        // step 4.表格内容
        int realRow = 1;
        for (AnalysisResult.Group group : groupList) {
            word.getXwpfTableHelper().mergeCellsVertically(table, 0, realRow, realRow + group.getDimenStatisticsList().size() - 1);
            table.getRow(realRow).getCell(0).setText(group.getGroupName());
            for (int j = 0; j < group.getDimenStatisticsList().size(); j++) {
                DimenStatistics dimenStatistics = group.getDimenStatisticsList().get(j);
                table.getRow(realRow).getCell(1).setText(dimenStatistics.getDimName());
                table.getRow(realRow).getCell(2).setText(String.valueOf(dimenStatistics.getAvg()));
                table.getRow(realRow).getCell(3).setText(String.valueOf(dimenStatistics.getStd()));
                word.getXwpfTableHelper().setTableRowBorder(table.getRow(realRow), STBorder.SINGLE, 1L, "DDDDDD");
                realRow++;
            }
        }
    }

    /**
     * 差异分析
     *
     * @param document
     * @param diversityList
     */
    private void diffAnalysis(XWPFDocument document, List<AnalysisResult.Diversity> diversityList) {
        // step 1.标题
        XWPFParagraph subTitle = document.createParagraph();
        subTitle.setSpacingBetween(3, LineSpacingRule.AUTO);
        XWPFRun subTitleRun = subTitle.createRun();
        subTitleRun.setFontFamily("宋体");
        subTitleRun.setFontSize(12);
        subTitleRun.setBold(true);
        subTitleRun.setText("二、差异分析");

        // step 2.创建表格
        long count = diversityList.stream().mapToLong(u -> u.getSectionList().size()).sum();
        XWPFTable table = document.createTable((int) (count + 1), 7);
        word.getXwpfTableHelper().setTableRowsHeight(table, 600, null);
        for (int i = 0; i < count + 1; i++) {
            word.getXwpfTableHelper().setTableRowBorder(table.getRow(i), STBorder.SINGLE, 1L, "DDDDDD");
            word.getXwpfTableHelper().setRowAlign(table.getRow(i), XWPFTableCell.XWPFVertAlign.CENTER, STJc.CENTER);
        }
        table.setWidth("100%");
        // step 3.设置表头内容和样式
        XWPFTableRow header = table.getRow(0);
        header.getCell(0).setText("维度名称");
        header.getCell(1).setText("差异分析");
        header.getCell(2).setText("平方和");
        header.getCell(3).setText("自由度");
        header.getCell(4).setText("均方");
        header.getCell(5).setText("F值");
        header.getCell(6).setText("P值");
        for (XWPFTableCell tableCell : header.getTableCells()) {
            tableCell.setColor("6CA1DD");
        }
        word.getXwpfTableHelper().setTableRowBorder(table.getRow(0), STBorder.SINGLE, 1L, "DDDDDD");

        int realRow = 1;
        for (AnalysisResult.Diversity diversity : diversityList) {
            word.getXwpfTableHelper().mergeCellsVertically(table, 0, realRow, realRow + diversity.getSectionList().size() - 1);
            table.getRow(realRow).getCell(0).setText(diversity.getDimenName());
            word.getXwpfTableHelper().mergeCellsVertically(table, 5, realRow, realRow + diversity.getSectionList().size() - 1);
            word.getXwpfTableHelper().mergeCellsVertically(table, 6, realRow, realRow + diversity.getSectionList().size() - 1);
            table.getRow(realRow).getCell(5).setText(String.valueOf(diversity.getF()));
            table.getRow(realRow).getCell(6).setText(diversity.getP());
            for (int j = 0; j < diversity.getSectionList().size(); j++) {
                AnalysisResult.Diversity.Section section = diversity.getSectionList().get(j);
                table.getRow(realRow).getCell(1).setText(section.getSectionName());
                table.getRow(realRow).getCell(2).setText(String.valueOf(section.getSS()));
                table.getRow(realRow).getCell(3).setText(String.valueOf(section.getDF()));
                table.getRow(realRow).getCell(4).setText(String.valueOf(section.getMS() == null ? "--" : section.getMS()));
                realRow++;
            }
        }
    }

    private void conclusion(XWPFDocument document, String conclusion) {

        // step 1.标题
        XWPFParagraph subTitle = document.createParagraph();
        subTitle.setSpacingBetween(3, LineSpacingRule.AUTO);
        XWPFRun subTitleRun = subTitle.createRun();
        subTitleRun.setFontFamily("宋体");
        subTitleRun.setFontSize(12);
        subTitleRun.setBold(true);
        subTitleRun.setText("三、结论");

        XWPFParagraph conclusionPara = document.createParagraph();
        XWPFRun conclusionRun = conclusionPara.createRun();
        conclusionRun.setFontFamily("宋体");
        conclusionRun.setFontSize(12);
        conclusionRun.setText("各团体间在总评上得分差异不显著（F=0.00，P>0.05）");
    }

    /**
     * 设置标题样式
     *
     * @param docxDocument
     * @param strStyleId
     * @param headingLevel
     */
    public void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) {

        CTStyle ctStyle = CTStyle.Factory.newInstance();
        ctStyle.setStyleId(strStyleId);

        CTString styleName = CTString.Factory.newInstance();
        styleName.setVal(strStyleId);
        ctStyle.setName(styleName);

        CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
        indentNumber.setVal(BigInteger.valueOf(headingLevel));

        // lower number > style is more prominent in the formats bar
        ctStyle.setUiPriority(indentNumber);

        CTOnOff onoffnull = CTOnOff.Factory.newInstance();
        ctStyle.setUnhideWhenUsed(onoffnull);

        // style shows up in the formats bar
        ctStyle.setQFormat(onoffnull);

        // style defines a heading of the given level
        CTPPr ppr = CTPPr.Factory.newInstance();
        ppr.setOutlineLvl(indentNumber);
        ctStyle.setPPr(ppr);

        XWPFStyle style = new XWPFStyle(ctStyle);

        // is a null op if already defined
        XWPFStyles styles = docxDocument.createStyles();

        style.setType(STStyleType.PARAGRAPH);
        styles.addStyle(style);

    }

}
